#!/bin/sh

setup_mysql()
{
	local mnt_point=$1
	systemctl stop mariadb.service

	# fix "Neither host 'lkp-bdw-ex1' nor 'localhost'
	# could be looked up with '/usr/sbin/resolveip'"
	# from mysql_install_db on Debian.
	[ ! -x /usr/sbin/resolveip ] && \
	ln -s $(which resolveip) /usr/sbin/resolveip

	mkdir -p $mnt_point/mysql
	mysql_install_db --datadir="$mnt_point/mysql" --user=mysql

	# fix "FATAL: error 1040: Too many connections"
	local max_conn=100
	if [ -n "$nr_threads" ] && [ "$nr_threads" -gt 100 ]; then
		max_conn=$((nr_threads * 2))
	elif [ -n "$nr_task" ] && [ "$nr_task" -gt 100 ]; then
		max_conn=$((nr_task * 2))
	fi

	# /usr/libexec/mysqld is used on RHEL/Centos
	# /usr/bin/mysql is used on Debian/Ubuntu
	# /usr/bin/haswell/mysql is used on Clear Linux
	local exec_mysqld='mysqld'
	mysqld --version >/dev/null 2>&1 || exec_mysqld='/usr/libexec/mysqld'
	$exec_mysqld --datadir="$mnt_point/mysql" --max-connections="$max_conn" --skip-grant-tables --user=mysql &
}

[ -n "$mount_points" ] || { echo "empty mount_points, disk failed?" >&2; exit; }

mnt_point="${mount_points%% *}"
[ -f /var/run/mysqld/mysqld.sock ] || {
	# ERROR: There's not enough space in /var/lib/mysql/
	# dpkg: error processing archive /opt/deb/mariadb-server-10.3_1%3a10.3.23-0+deb10u1_amd64.deb (--install):
	#   new mariadb-server-10.3 package pre-installation script subprocess returned error exit status 1
	mkdir -p $mnt_point/var_lib_mysql
	mount --bind $mnt_point/var_lib_mysql /var/lib/mysql
	dpkg --force-all -i /opt/deb/mariadb*
}
setup_mysql "$mnt_point"
